<template>
  <div class="product-form-view">
    <div class="page-header">
      <h1>{{ isEdit ? '编辑商品' : '新建商品' }}</h1>
      <p>{{ isEdit ? '修改商品信息' : '添加新的商品到系统中' }}</p>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="product-form"
    >
      <!-- 基本信息 -->
      <el-card class="form-section" shadow="hover">
        <template #header>
          <div class="section-header">
            <el-icon><InfoFilled /></el-icon>
            <span>基本信息</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入商品名称"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品SKU" prop="sku">
              <el-input
                v-model="form.sku"
                placeholder="请输入商品SKU"
                maxlength="50"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="商品分类" prop="category_id">
              <el-tree-select
                v-model="form.category_id"
                :data="categoryOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                placeholder="请选择商品分类"
                check-strictly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="草稿" value="draft" />
                <el-option label="上架" value="active" />
                <el-option label="下架" value="inactive" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-card>

      <!-- 价格库存 -->
      <el-card class="form-section" shadow="hover">
        <template #header>
          <div class="section-header">
            <el-icon><Money /></el-icon>
            <span>价格库存</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="销售价格" prop="price">
              <el-input-number
                v-model="form.price"
                :min="0"
                :precision="2"
                placeholder="0.00"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市场价格">
              <el-input-number
                v-model="form.market_price"
                :min="0"
                :precision="2"
                placeholder="0.00"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库存数量" prop="stock_quantity">
              <el-input-number
                v-model="form.stock_quantity"
                :min="0"
                placeholder="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 商品图片 -->
      <el-card class="form-section" shadow="hover">
        <template #header>
          <div class="section-header">
            <el-icon><Picture /></el-icon>
            <span>商品图片</span>
          </div>
        </template>

        <!-- 主图 -->
        <el-form-item label="商品主图" prop="main_image_url">
          <div class="image-upload-section">
            <el-upload
              class="main-image-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleMainImageSuccess"
              :before-upload="beforeImageUpload"
              accept="image/*"
              name="productImages"
            >
              <img v-if="form.main_image_url" :src="form.main_image_url" class="main-image" />
              <el-icon v-else class="main-image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">
              <p>点击上传商品主图</p>
              <p class="tip-text">建议尺寸：800x800px，支持JPG、PNG格式，大小不超过2MB</p>
            </div>
          </div>
        </el-form-item>

        <!-- 轮播图 -->
        <el-form-item label="轮播图片">
          <div class="gallery-upload-section">
            <el-upload
              class="gallery-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :file-list="galleryFileList"
              :on-success="handleGallerySuccess"
              :on-remove="handleGalleryRemove"
              :before-upload="beforeImageUpload"
              accept="image/*"
              multiple
              list-type="picture-card"
              name="productImages"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">
              <p class="tip-text">最多上传9张轮播图片，建议尺寸：800x800px</p>
            </div>
          </div>
        </el-form-item>
      </el-card>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? '更新商品' : '创建商品' }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled, Money, Picture, Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

// 路由和状态
const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const formRef = ref()
const loading = ref(false)
const categoryOptions = ref<any[]>([])
const galleryFileList = ref<any[]>([])

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const form = reactive({
  name: '',
  sku: '',
  category_id: null,
  description: '',
  price: 0,
  market_price: null,
  stock_quantity: 0,
  main_image_url: '',
  gallery_image_urls: [] as string[],
  status: 'draft'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '商品名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  sku: [
    { required: true, message: '请输入商品SKU', trigger: 'blur' },
    { min: 2, max: 50, message: 'SKU长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category_id: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入销售价格', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
          callback(new Error('请输入销售价格'))
        } else if (isNaN(value) || parseFloat(value) <= 0) {
          callback(new Error('价格必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  stock_quantity: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
  ],
  main_image_url: [
    { required: true, message: '请上传商品主图', trigger: 'change' }
  ]
}

// 上传配置
const uploadUrl = computed(() => `${import.meta.env.VITE_API_BASE_URL}/upload/product-images`)
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${authStore.token}`
}))

// 方法
const loadCategories = async () => {
  try {
    const response = await request.get('/categories/tree')
    categoryOptions.value = response.data
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
  }
}

const loadProduct = async (id: string) => {
  try {
    loading.value = true
    const response = await request.get(`/products/${id}`)
    const product = response.data

    // 填充表单数据
    Object.assign(form, {
      name: product.name,
      sku: product.sku,
      category_id: product.category_id,
      description: product.description || '',
      price: product.price ? parseFloat(product.price) : null,
      market_price: product.market_price ? parseFloat(product.market_price) : null,
      stock_quantity: product.stock_quantity ? parseInt(product.stock_quantity) : 0,
      main_image_url: product.main_image_url || '',
      gallery_image_urls: product.gallery_image_urls || [],
      status: product.status
    })

    // 设置轮播图文件列表
    if (product.gallery_image_urls && product.gallery_image_urls.length > 0) {
      galleryFileList.value = product.gallery_image_urls.map((url: string, index: number) => ({
        name: `gallery-${index + 1}`,
        url: url,
        uid: Date.now() + index
      }))
    }

  } catch (error: any) {
    console.error('加载商品失败:', error)
    ElMessage.error(error.response?.data?.message || '加载商品失败')
    router.push('/products')
  } finally {
    loading.value = false
  }
}

const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleMainImageSuccess = (response: any) => {
  if (response.success) {
    // 后端返回的是数组，取第一个元素
    const uploadedFile = Array.isArray(response.data) ? response.data[0] : response.data
    form.main_image_url = uploadedFile.url
    ElMessage.success('主图上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleGallerySuccess = (response: any, file: any) => {
  if (response.success) {
    // 后端返回的是数组，取第一个元素
    const uploadedFile = Array.isArray(response.data) ? response.data[0] : response.data
    form.gallery_image_urls.push(uploadedFile.url)
    ElMessage.success('轮播图上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleGalleryRemove = (file: any) => {
  const index = galleryFileList.value.findIndex(item => item.uid === file.uid)
  if (index > -1) {
    form.gallery_image_urls.splice(index, 1)
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const submitData = { ...form }

    if (isEdit.value) {
      await request.put(`/products/${route.params.id}`, submitData)
      ElMessage.success('商品更新成功')
    } else {
      await request.post('/products', submitData)
      ElMessage.success('商品创建成功')
    }

    router.push('/products')

  } catch (error: any) {
    if (error.response) {
      ElMessage.error(error.response.data?.message || '操作失败')
    } else if (error !== false) { // 表单验证失败时error为false
      ElMessage.error('操作失败')
    }
  } finally {
    loading.value = false
  }
}

const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消吗？未保存的更改将会丢失。',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    )
    router.push('/products')
  } catch {
    // 用户取消
  }
}

// 生命周期
onMounted(async () => {
  await loadCategories()

  if (isEdit.value && route.params.id) {
    await loadProduct(route.params.id as string)
  }
})
</script>

<style scoped>
.product-form-view {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.form-section {
  margin-bottom: 24px;
  border-radius: 8px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.image-upload-section {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.main-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.main-image-uploader:hover {
  border-color: #409eff;
}

.main-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  text-align: center;
  line-height: 148px;
}

.main-image {
  width: 148px;
  height: 148px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  flex: 1;
}

.upload-tip p {
  margin: 0 0 4px 0;
  color: #606266;
}

.tip-text {
  font-size: 12px;
  color: #909399;
}

.gallery-upload-section .upload-tip {
  margin-top: 8px;
}

.form-actions {
  text-align: center;
  padding: 24px 0;
  border-top: 1px solid #ebeef5;
  margin-top: 24px;
}

.form-actions .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-form-view {
    margin: 0 16px;
  }

  .image-upload-section {
    flex-direction: column;
  }
}
</style>
